package com.fw.system.comm.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fw.constant.Constant;
import com.fw.core.redis.RedisCache;
import com.fw.system.comm.mapper.FwDistrictMapper;
import com.fw.system.comm.mode.entity.District;
import com.fw.system.comm.mode.vo.DistrictVo;
import com.fw.system.comm.service.DistrictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DistrictServiceImpl  extends ServiceImpl<FwDistrictMapper, District> implements DistrictService {

    @Autowired
    private FwDistrictMapper fwDistrictMapper;

    @Autowired
    private RedisCache redisCache;

    @Override
    public List<DistrictVo> findAll() {
        return fwDistrictMapper.findAll();
    }

    /**
     * 同步 数据库中的信息，到redis 中
     */
    @Override
    public void synchronizeDistrict() {
        log.info("同步省市区街道四级联动开始！");
        List<DistrictVo> districtVoList = findAll();
        // 查询父节点的
        String districtData = Constant.RedisDistrict.DISTRICT_DATA;
        String codeData = Constant.RedisDistrict.DISTRICT_DATA;
        redisCache.deleteObject(districtData);
        redisCache.deleteObject(codeData);
        Set<Integer> pids = districtVoList.parallelStream().map(item -> item.getPid()).collect(Collectors.toSet());
        for (Integer pid : pids) {
            redisCache.setCacheMapValue(districtData,String.valueOf(pid),districtVoList.parallelStream().filter(item -> item.getPid().equals(pid)).collect(Collectors.toList()));
        }
        // 同步 code 信息
        for (DistrictVo districtVo : districtVoList) {
            redisCache.setCacheMapValue(codeData,districtVo.getCode(),districtVo);
        }
        log.info("同步省市区街道四级联动结束！");

    }

    @Override
    public List<DistrictVo> findPid(Integer pid) {
        String districtData = Constant.RedisDistrict.DISTRICT_DATA;
        return redisCache.getCacheMapValue(districtData,String.valueOf(pid));
    }

    @Override
    public String codeConversionName(String code) {
        String codeData = Constant.RedisDistrict.DISTRICT_DATA;
        Object object = redisCache.getCacheMapValue(codeData, code);
        if (Objects.isNull(object)) return null;
        return JSONUtil.toBean(JSONUtil.parseObj(JSONUtil.toJsonStr(object)),DistrictVo.class).getName();
    }

}
